Method Recursion:
In Java, a method that calls itself is known as a recursive method, and this process is known as recursion. Recursion can make code look simple and elegant. However, it can lead to complex behavior.
Here’s the basic syntax of a recursive method:
Recursive method basic syntax
returnType methodName() {
// code to be executed
methodName(); // calling the same method
}
Example 1: Factorial Calculation
A classic example of recursion is the calculation of the factorial of a number. The factorial of a number n is the product of all positive integers less than or equal to n. It’s denoted by n!.
Factorial Calculation in java using recursion example
public class Main{
static int factorial(int n) {
if (n == 1)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: " + factorial(5));
}
}
Output
Factorial of 5 is: 120
In the above example, the factorial method calls itself until it reaches the base case where n == 12.
Example 2: Fibonacci Series
Another common example of recursion is generating the Fibonacci series. In this series, each number is the sum of the two preceding ones.
Fibonacci series example using recursion in java
public class Main{
static int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int n = 10;
System.out.println("Fibonacci series up to " + n + ":");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
Output
Fibonacci series up to 10:
0 1 1 2 3 5 8 13 21 34
In the above example, the fibonacci method calls itself twice until it reaches the base case where n <= 12.